
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

/***
 * <hr>
 * service class to run he service
 */

public class ImageToHTML {

	static final String IMG_FOLDER_PATH = "..\\images\\";
	static final String HTML_FILE = "..\\index.html";
	
	static final String OUTPUT_FILE_REPLACER_TAG_HEADER = "<dl class=\"slidedeck\">";
	static final String OUTPUT_FILE_REPLACER_TAG_ENDER = "</dl>";

	static List<String> dtList = new ArrayList<String>(5);
	static List<String> ddList = new ArrayList<>(5);

	static Map<String, String> fileNames = new LinkedHashMap<String, String>();// slidenumber,path
	static int counter = 1;

	//private String pathToHtmlFile;
	private File inputFolder = null;
	private File[] files = null;

	public ImageToHTML() {
		this.inputFolder = new File(IMG_FOLDER_PATH);

	}

	

	private void doService() throws ImageException {
		print("image to html file service statrted");
		if (!Util.isNullObject(inputFolder)) {
			if (inputFolder.isDirectory()) {
				print("Processing files..");
				// files=inputFolder.listFiles();
				files = getImgFiles(inputFolder);

				if (!Util.isNullObject(files)) {
					appendIntoFile(HTML_FILE, processFileNames(files));
				} else {
					throw new ImageException("In do service of "
							+ this.getClass().getName() + " no files found");
				}
			} else {
				throw new ImageException("input folder is not directory");
			}
		} else {
			throw new ImageException("Cannot open input folder");
		}
		print("image to html file service ended");

	}

	public static void main(String args[]) {
		ImageToHTML iths = new ImageToHTML();
		try {
			iths.doService();
		} catch (Exception e) {
			System.out.println(e.toString());
		}
	}

	private static File[] getImgFiles(File folder) {
		System.out.println("Getting files");

		FilenameFilter imgFilter = new FilenameFilter() {
			public boolean accept(File dir, String name) {
				String regEx = "(img-?\\d?\\d?\\d?\\d?\\d?)(\\.)(png|gif|jpg)";
				return (name.matches(regEx));
			}
		};

		File[] files = folder.listFiles(imgFilter);

		/*for (File f : files) {
			print(f.getName() + ",");
		}
		print("\n");*/

		return files;
	}

	static Map<String, String> processFileNames(File[] imgFiles)
			throws ImageException {
		String fileName;
		if (!Util.isNullObject(imgFiles) && imgFiles.length > 0) {
			for (File f : imgFiles) {
				fileName = f.getName();
				fileNames.put(String.valueOf(counter), "images/" + fileName);
				System.out.printf(" <Slide No = %d , image = %s>\n", counter,
						fileName);
				counter++;

			}

		} else {
			throw new ImageException("No image files present in folder ");
		}
		return (null == fileNames) ? null : fileNames;
	}

	static void print(String msg) {
		System.out.print("<<<<<" + msg + ">>>>>");
	}
	
	static void print(String tag, List<String> list) {

		System.out.println("Printing Tag: " + tag + "\n");

		for (String s : list) {
			System.out.print(s);
		}

		System.out.print("\n");
	}

	// common utility methods

	

	/*public static boolean isNullObject(Object object) {
		return (null == object) ? true : false;
	}*/

	

	// File processes

	public static void appendIntoFile(String pathToFile,
			Map<String, String> fileNames) throws ImageException {

		if (!Util.isNullOrEmptySring(pathToFile) && !Util.isNullObject(fileNames)) {
			makeDtsDds(fileNames);// dt tags and dd tags with image srcs are
									// made
			print("dt", dtList);
			print("dd", ddList);
			String toAppend = makeDtDdStringToAppend(dtList, ddList);// data to
																		// append
																		// between
																		// the
																		// tags
			String entireFileLoaded = loadEntireFile(pathToFile);// load entire
																	// file in
																	// memory
			splitAndWriteDataToTempFile(entireFileLoaded, pathToFile, toAppend);
		} else {
			throw new ImageException(
					"in append to file empty path to file or no file names passed");
		}
	}

	private static void makeDtsDds(Map<String, String> imgFileNames)
			throws ImageException {
		if (!Util.isNullObject(imgFileNames)) {
			for (Map.Entry<String, String> entry : imgFileNames.entrySet()) {
				dtList.add("<dt>" + "</dt>");
				ddList.add("<dd>"// <dd>
						+ "\n" + "<img "// <img
						+ "src="// src=
						+ "\"" // "
						+ entry.getValue()// path e.g c:\\abc:\\
						+ "\"" // "
						+ "/>"// />
						+ "\n" + "</dd>");// </dd>
			}
		} else {
			throw new ImageException(
					"in makeDtsDds empty path to file or no file names passed");
		}
	}

	private static String makeDtDdStringToAppend(List<String> dt,
			List<String> dd) throws ImageException {
		String oneBigString = "\n" + OUTPUT_FILE_REPLACER_TAG_HEADER;
		if (!Util.isNullObject(dt) && !Util.isNullObject(dd)) {
			for (int i = 0; i < dt.size() && i < dd.size(); i++) {
				oneBigString += "\n" + dt.get(i) + "\n" + dd.get(i) + "\n";
			}
		} else {
			throw new ImageException(
					"in makeDtDdString empty dt or dd list passed");
		}
		return oneBigString += OUTPUT_FILE_REPLACER_TAG_ENDER;
	}

	private static String loadEntireFile(String pathToFile)
			throws ImageException {
		Scanner s = null;
		String entireFile = "";
		if (!Util.isNullOrEmptySring(pathToFile)) {
			try {
				s = new Scanner(new File(pathToFile));
				while (s.hasNextLine()) {

					entireFile += s.nextLine() + "\n";
				}
			} catch (FileNotFoundException e) {
				throw new ImageException(
						"file not found for loading into memory");
			}

			if (!Util.isNullObject(s)) {
				s.close();
			}
		} else {
			throw new ImageException(
					"in loadentirefile empty path to file passed");
		}
		return entireFile;
	}

	private static void splitAndWriteDataToTempFile(String entireFileString,
			String pathToFile, String dataToAppend) throws ImageException {
		String fileSplittedAtOpenDl[] = null;
		String fileSplittedAtEndDl[] = null;
		if (!Util.isNullOrEmptySring(entireFileString)
				&& !Util.isNullOrEmptySring(pathToFile)
				&& !Util.isNullOrEmptySring(dataToAppend)) {
			fileSplittedAtOpenDl = entireFileString
					.split(OUTPUT_FILE_REPLACER_TAG_HEADER);
			fileSplittedAtEndDl = fileSplittedAtOpenDl[1]
					.split(OUTPUT_FILE_REPLACER_TAG_ENDER);

			BufferedWriter bw = null;

			try {
				bw = new BufferedWriter(new FileWriter(pathToFile));
				bw.write(fileSplittedAtOpenDl[0] + dataToAppend
						+ fileSplittedAtEndDl[1]);
				bw.close();
			} catch (IOException e) {
				throw new ImageException(
						"error creating tempory file due to " + e);
			}
		}
	}

	
}
